package net.edu_soft.ec.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Set;
import java.util.Map.Entry;

import net.edu_soft.ec.asset.constant.CloudFileUrlConstant;
import org.apache.commons.lang3.StringUtils;

public class CheckFileType {

    // private static Trace logger = Trace.getTrace(CheckFileType.class);
    // 缓存文件头信息-文件头信息
    public static final HashMap<String, String> mFileTypes = new HashMap<String, String>();

    static {
        // images
        mFileTypes.put("FFD8FF", "jpg," + CloudFileUrlConstant.IMAGE_FILE_URL);
        mFileTypes.put("89504E47", "png," + CloudFileUrlConstant.IMAGE_FILE_URL);
        mFileTypes.put("47494638", "gif," + CloudFileUrlConstant.IMAGE_FILE_URL);
        mFileTypes.put("49492A00", "tif," + CloudFileUrlConstant.IMAGE_FILE_URL);
        mFileTypes.put("424D", "bmp," + CloudFileUrlConstant.REST_FILE_URL);
        //
        mFileTypes.put("41433130", "dwg," + CloudFileUrlConstant.REST_FILE_URL); // CAD
        mFileTypes.put("38425053", "psd," + CloudFileUrlConstant.REST_FILE_URL);
        mFileTypes.put("7B5C727466", "rtf," + CloudFileUrlConstant.REST_FILE_URL); // 日记本
        mFileTypes.put("3C3F786D6C", "xml," + CloudFileUrlConstant.REST_FILE_URL);
        mFileTypes.put("68746D6C3E", "html," + CloudFileUrlConstant.REST_FILE_URL);
        mFileTypes.put("44656C69766572792D646174653A", "eml," + CloudFileUrlConstant.REST_FILE_URL); // 邮件
        mFileTypes.put("D0CF11E0", "doc," + CloudFileUrlConstant.DOC_FILE_URL);
        mFileTypes.put("D0CF11E0", "xls," + CloudFileUrlConstant.DOC_FILE_URL);// excel2003版本文件
        mFileTypes.put("5374616E64617264204A", "mdb," + CloudFileUrlConstant.REST_FILE_URL);
        mFileTypes.put("252150532D41646F6265", "ps," + CloudFileUrlConstant.REST_FILE_URL);
        mFileTypes.put("255044462D312E", "pdf," + CloudFileUrlConstant.DOC_FILE_URL);
        mFileTypes.put("504B0304", "docx," + CloudFileUrlConstant.DOC_FILE_URL);
        mFileTypes.put("504B0304", "xlsx," + CloudFileUrlConstant.DOC_FILE_URL);// excel2007以上版本文件
        mFileTypes.put("52617221", "rar," + CloudFileUrlConstant.YS_FILE_URL);
        mFileTypes.put("57415645", "wav," + CloudFileUrlConstant.REST_FILE_URL);
        mFileTypes.put("41564920", "avi," + CloudFileUrlConstant.REST_FILE_URL);
        mFileTypes.put("2E524D46", "rm," + CloudFileUrlConstant.REST_FILE_URL);
        mFileTypes.put("000001BA", "mpg," + CloudFileUrlConstant.REST_FILE_URL);
        mFileTypes.put("000001B3", "mpg," + CloudFileUrlConstant.REST_FILE_URL);
        mFileTypes.put("6D6F6F76", "mov," + CloudFileUrlConstant.REST_FILE_URL);
        mFileTypes.put("3026B2758E66CF11", "asf," + CloudFileUrlConstant.REST_FILE_URL);
        mFileTypes.put("4D546864", "mid," + CloudFileUrlConstant.REST_FILE_URL);
        mFileTypes.put("1F8B08", "gz," + CloudFileUrlConstant.YS_FILE_URL);
    }

    /**
     * @return 文件头信息
     * @author liang.pan
     * <p>
     * 方法描述：根据输入流获取文件头信息
     */
    public static String getFileType(InputStream inputStream) {
        return mFileTypes.get(getFileHeader(inputStream));
    }

    /**
     * @return 文件头信息
     * @author liang.pan
     * <p>
     * 方法描述：根据输入流获取文件头信息
     */
    public static String getFileHeader(InputStream inputStream) {
        InputStream is = null;
        String value = null;
        try {
            is = inputStream;
            byte[] b = new byte[4];
            /*
             * int read() 从此输入流中读取一个数据字节。int read(byte[] b) 从此输入流中将最多 b.length 个字节的数据读入一个
             * byte 数组中。 int read(byte[] b, int off, int len) 从此输入流中将最多 len 个字节的数据读入一个 byte
             * 数组中。
             */
            is.read(b, 0, b.length);
            value = bytesToHexString(b);
        } catch (Exception e) {
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
        //System.out.println(">>>>>文件的头部信息:" + value);
        if (StringUtils.startsWith(value, "FFD8FF")) {
            value = value.substring(0, 6);
        }
        return value;
    }

    /**
     * @param src 要读取文件头信息的文件的byte数组
     * @return 文件头信息
     * @author liang.pan
     * <p>
     * 方法描述：将要读取文件头信息的文件的byte数组转换成string类型表示
     */
    private static String bytesToHexString(byte[] src) {
        StringBuilder builder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        String hv;
        for (int i = 0; i < src.length; i++) {
            // 以十六进制（基数 16）无符号整数形式返回一个整数参数的字符串表示形式，并转换为大写
            hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
            if (hv.length() < 2) {
                builder.append(0);
            }
            builder.append(hv);
        }
        return builder.toString();
    }

    /**
     * @param inputStream 输入流文件信息
     * @return 文件后缀
     * @Description:传入文件判断文件类型
     */
    public static String getFileTypeName(InputStream inputStream) {
        String suffixName = null;
        if (inputStream!=null) {
            String header = CheckFileType.getFileHeader(inputStream);//
//            System.out.println(header);
            if (header != null) {
                Set<Entry<String, String>> entrySet = mFileTypes.entrySet();
                for (Entry<String, String> entry : entrySet) {
                    if (entry.getKey().indexOf(header) != -1) {// 判断是否存在该文件后缀,匹配是否存在该字符串
                        suffixName = entry.getValue();//得到文件后缀
                    }
                }
            }
        }
        return suffixName;
    }

    /***
     * 获得上传的文件类型所属的文件夹
     * @param inputStream 输入流
     * @return
     */
    public static String getFolderName(InputStream inputStream) {
        String name = getFileTypeName(inputStream);
        if (name != null) {
            return name.split(",")[1];//截取最后一个文件夹名
        }
        return null;
    }

}